package com.example.service;

import com.example.config.MqttIntegrationConfig;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MqttIntegrationService {

    @Autowired
    private MessageChannel mqttOutboundChannel;

    @Autowired
    private MqttIntegrationConfig mqttConfig;

    /**
     * 处理接收到的MQTT消息
     */
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMessage(Message<?> message) {
        if (message == null) {
            log.error("接收的消息为空");
            return;
        }

        // 从消息中获取主题（若消息头中包含"mqtt_topic" 、 "mqtt_receivedTopic"）
        String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
        if (topic == null || topic.isEmpty()) {
            log.error("消息头中未指定mqtt_topic");
            return;
        }

        // 获取消息内容
        String payload = message.getPayload().toString();

        log.info("收到MQTT消息 - 主题: {}, 内容: {}", topic, payload);

        // 示例：根据主题处理不同类型的消息
        switch (topic) {
            case "sensor/data":
                processSensorData(payload);
                break;
            case "device/status":
                processDeviceStatus(payload);
                break;
            case "test/topic":
                processTestMessage(payload);
                break;
            default:
                log.info("未知主题消息: {}", topic);
        }
    }

    /**
     * 发布消息到MQTT主题
     */
    public void publishMessage(String topic, String message) {
        Message<String> mqttMessage = MessageBuilder
                .withPayload(message)
                .setHeader("mqtt_topic", topic)
                .build();

        mqttOutboundChannel.send(mqttMessage);
        log.info("发布MQTT消息 - 主题: {}, 内容: {}", topic, message);
    }

    /**
     * 处理传感器数据
     */
    private void processSensorData(String data) {
        log.info("处理传感器数据: {}", data);
        // 这里可以添加数据处理逻辑
        // 例如：数据验证、存储、转发等
    }

    /**
     * 处理设备状态
     */
    private void processDeviceStatus(String status) {
        log.info("处理设备状态: {}", status);
        // 这里可以添加状态处理逻辑
        // 例如：状态更新、告警等
    }

    /**
     * 处理测试消息
     */
    private void processTestMessage(String message) {
        log.info("处理测试消息: {}", message);
        // 回复测试消息
        publishMessage("test/response", "收到测试消息: " + message);
    }
}
